<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Order as OrderModel;
use app\index\model\DeliveryAddress;
use app\index\model\Car;
use app\index\model\Collection;
use app\admin\model\Goods;

class Order extends Controller
{
	private  $order;
    public function _initialize() {
        $this->order = new OrderModel();
    }

    public function index()
    {
    	$uid = session('user')['id'];
    	$order_no = input('get.order_no');
    	
    	// 查询该用户的默认地址
    	$addressModel = new DeliveryAddress();
    	$default_addr = $addressModel->where(['uid'=>$uid,'status'=>1])->find();
    	// 其他地址
    	$other_addr = $addressModel->where(['uid'=>$uid,'status'=>0])->select();

    	// 查询该订单相关信息
    	$order_info = $this->order->where('order_no',$order_no)->select();

    	// 总计
    	$sum = $this->order->where('order_no',$order_no)->sum('total_price');
    	return $this->fetch('',[
    		'default_addr' => $default_addr,
    		'other_addr' => $other_addr,
    		'order_info' => $order_info,
    		'sum' => $sum,
    		'order_no' => $order_no,
    	]);
    }

    // 从购物车添加临时订单（未完成）
	public function add_order()
	{
		$data = input('post.');
		$order_num = time() . mt_rand(10000,99999);
		$order_no[0] = $order_num;
		$order_no[1] = $order_num;
		$user_id = session('user')['id'];
		$uid[0] = $user_id;
		$uid[1] = $user_id;
		$gid_arr = explode(',',rtrim($data['ids'],','));
		$gname_arr = explode(',',rtrim($data['gname'],','));
		$picture_arr = explode(',', rtrim($data['picture'],','));
		$price_arr = explode(',', rtrim($data['price'],','));
		$num_arr = explode(',', rtrim($data['num'],','));
		$total_price_arr = explode(',', rtrim($data['subtotal'],','));

		// 生成订单，删除购物车数据
		$shop_cart = new Car();
		$gids = rtrim($data['ids'],',');
		$shop_cart->where('gid','in',$gids)->delete();
		for ($i=0; $i <count($gid_arr) ; $i++) {
			$list[$i] = [
				'order_no' => $order_no[$i],
				'uid' => $uid[$i],
				'gid' => $gid_arr[$i],
				'gname' => $gname_arr[$i],
				'picture' => $picture_arr[$i],
				'num' => $num_arr[$i],
				'price' => $price_arr[$i],
				'total_price' => $total_price_arr[$i]
			];
		}
			
		foreach ($list as $data) {
			$res = $this->order->data($data,true)->isUpdate(false)->save();
		}
		if ($res) {
			$this->result("/index/order/index.html?order_no=$order_no[0]", 1, 'success');
		} else {
			$this->result($_SERVER['HTTP_REFERER'], 0, 'error');
		}
	}

	// 用户点立即购买直接生产订单
	public function create_order()
	{
		$data = input('post.');
		$order_no = time() . mt_rand(10000,99999);
		$data['order_no'] = $order_no;
		$total = $data['price'] * $data['num'];
		$data['total_price'] = $total;
		$res = $this->order->data($data,true)->isUpdate(false)->save();
		if ($res) {
			$this->result("/index/order/index.html?order_no=$order_no", 1, 'success');
		}else{
			$this->result($_SERVER['HTTP_REFERER'], 0, 'error');
		}
	}

	// 通过用户收藏购买
	public function collection_pay()
	{
		$data = input('post.');
		$gid = $data['gid'];
		$collection = new Collection();
		$coll = $collection->getByGid($gid)->toArray();
		$order_no = time() . mt_rand(10000,99999);
		$coll['order_no'] = $order_no;
		$coll['num'] = 1;
		$coll['total_price'] = $coll['price'] * $coll['num'];
		unset($coll['id']);
		$res = $this->order->data($coll,true)->isUpdate(false)->save();
		if ($res) {
			$this->result("/index/order/index.html?order_no=$order_no", 1, 'success');
		}else{
			$this->result($_SERVER['HTTP_REFERER'], 0, 'error');
		}
	}

	// 用户提交订单
	public function order_submit()
	{
		$data = input('post.');
		// 更改订单状态
		$update = [
			'status' => 1,
			'aid' => $data['aid'],
		];
		$order_no = $data['order_no'];
		$res = $this->order->save($update,['order_no'=>$order_no]);
		if ($res) {
			$this->result("/index/order/order_pay.html?order_no=$order_no",1,'success');
		} else{
			$this->result($_SERVER['HTTP_REFERER'], 0, '提交失败');
		}
	}

	//下单支付 
	public function order_pay()
	{
		return $this->fetch();
	}

	// 确认支付
	public function paid()
	{
		$goodsModel = new Goods();
		$data = input('post.');
		$order_no = $data['value'];
		$orders = $this->order->where('order_no',$order_no)->select();
		foreach ($orders as $value) {
			$gid = $value->gid;
			$paid_num = $value->num;
			$sales = $goodsModel->where('id',$gid)->column('sales');
			// $final_sale = $paid_num + $sales;
			// dump($final_sale);exit;
			$goodsModel->save(['sales'=>$sales[0]+$paid_num],['id'=>$gid]);
		}
		// 修改订单状态
		$res = $this->order->save(['status'=>2],['order_no'=>$data['value']]);
		
		if ($res) {
			$this->result("/index/personal/order.html", 1, '支付成功');
		} else{
			$this->result($_SERVER['HTTP_REFERER'], 0, '支付失败');
		}
	}

	// 删除未完成订单
	public function delete($order_no)
	{
		$res = $this->order->where('order_no',$order_no)->delete();
		if ($res) {
			$this->result($_SERVER['HTTP_REFERER'], 1, '删除成功');
		} else{
			$this->result($_SERVER['HTTP_REFERER'], 0, '删除失败');
		}
	}

	// 用户确认收货
	public function confirm($order_no)
	{
		$res = $this->order->save(['status'=>4],['order_no'=>$order_no]);
		if ($res) {
			$this->result($_SERVER['HTTP_REFERER'], 1, '确认成功');
		} else{
			$this->result($_SERVER['HTTP_REFERER'], 0, '确认失败');
		}
	}



	// 选择收货地址
	public function sel_addr($id)
	{
		$addressModel = new DeliveryAddress();
		$seladdr = $addressModel->get($id);
		$data = $seladdr->toArray();
		$data['pro'] = getProvince($data['province']);
		$data['city'] = getProvince($data['city']);
		if ($seladdr) {
			return show(1,'success',$data);
		}
		return show(0,'error');
	}
}
